'use client';

import { useForm, Controller } from 'react-hook-form';
import { useEffect } from 'react';
import { TextField, Button, Stack, MenuItem } from '@mui/material';
import { DateTimePicker } from '@mui/x-date-pickers/DateTimePicker';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import dayjs from 'dayjs';
import ExamQuestions from './ExamQuestions';

// 定义可选的科目列表
const subjects = [
  '语文',
  '数学',
  '英语',
  '物理',
  '化学',
  '生物',
  '历史',
  '地理',
  '政治'
];

interface ExamFormProps {
  initialValues?: any;
  onFinish: (values: any) => Promise<void>;
  loading: boolean;
  submitText?: string;
}

export default function ExamForm({
  initialValues,
  onFinish,
  loading,
  submitText = '提交'
}: ExamFormProps) {
  const { control, handleSubmit, watch, setValue } = useForm({
    defaultValues: {
      title: initialValues?.title || '',
      subject: initialValues?.subject || '',
      description: initialValues?.description || '',
      examTime: [
        initialValues?.examTime?.[0] || dayjs(),
        initialValues?.examTime?.[1] || dayjs().add(1, 'hour')
      ],
      duration: initialValues?.duration || 60,
      totalScore: initialValues?.totalScore || 100,
      passingScore: initialValues?.passingScore || 60,
      questions: initialValues?.questions || []
    }
  });

  // 监听开始时间和考试时长的变化
  const startTime = watch('examTime.0');
  const duration = watch('duration');

  // 当开始时间或考试时长变化时，自动更新结束时间
  useEffect(() => {
    if (startTime && duration) {
      const endTime = dayjs(startTime).add(Number(duration), 'minutes');
      setValue('examTime.1', endTime);
    }
  }, [startTime, duration, setValue]);

  const onSubmit = async (values: any) => {
    try {
      const formattedValues = {
        title: values.title,
        subject: values.subject,
        description: values.description,
        startTime: values.examTime[0].toISOString(),
        endTime: values.examTime[1].toISOString(),
        duration: Number(values.duration),
        totalScore: Number(values.totalScore),
        passingScore: Number(values.passingScore),
        questions: values.questions.map((q: any) => ({
          id: q.id,
          score: q.score
        })) || []
      };
      await onFinish(formattedValues);
    } catch (error) {
      console.error('表单提交失败:', error);
    }
  };

  const subject = watch('subject');

  return (
    <LocalizationProvider dateAdapter={AdapterDayjs}>
      <form onSubmit={handleSubmit(onSubmit)} className="max-w-2xl">
        <Stack spacing={3}>
          <Controller
            name="title"
            control={control}
            rules={{ required: '请输入考试标题' }}
            render={({ field, fieldState: { error } }) => (
              <TextField
                {...field}
                label="考试标题"
                error={!!error}
                helperText={error?.message}
                fullWidth
              />
            )}
          />

          <Controller
            name="subject"
            control={control}
            rules={{ required: '请选择考试科目' }}
            render={({ field, fieldState: { error } }) => (
              <TextField
                {...field}
                select
                label="考试科目"
                error={!!error}
                helperText={error?.message}
                fullWidth
              >
                {subjects.map(subject => (
                  <MenuItem key={subject} value={subject}>
                    {subject}
                  </MenuItem>
                ))}
              </TextField>
            )}
          />

          <Controller
            name="description"
            control={control}
            rules={{ required: '请输入考试描述' }}
            render={({ field, fieldState: { error } }) => (
              <TextField
                {...field}
                label="考试描述"
                multiline
                rows={4}
                error={!!error}
                helperText={error?.message}
                fullWidth
              />
            )}
          />

          <Stack direction="row" spacing={2}>
            <Controller
              name="examTime.0"
              control={control}
              rules={{ required: '请选择开始时间' }}
              render={({ field: { onChange, value }, fieldState: { error } }) => (
                <DateTimePicker
                  label="开始时间"
                  value={value}
                  onChange={onChange}
                  slotProps={{
                    textField: {
                      fullWidth: true,
                      error: !!error,
                      helperText: error?.message
                    }
                  }}
                />
              )}
            />
            <Controller
              name="examTime.1"
              control={control}
              rules={{ required: '请选择结束时间' }}
              render={({ field: { onChange, value }, fieldState: { error } }) => (
                <DateTimePicker
                  label="结束时间"
                  value={value}
                  onChange={onChange}
                  disabled={true}
                  slotProps={{
                    textField: {
                      fullWidth: true,
                      error: !!error,
                      helperText: error?.message
                    }
                  }}
                />
              )}
            />
          </Stack>

          <Controller
            name="duration"
            control={control}
            rules={{ required: '请输入考试时长' }}
            render={({ field, fieldState: { error } }) => (
              <TextField
                {...field}
                label="考试时长（分钟）"
                type="number"
                inputProps={{ min: 1, max: 360 }}
                error={!!error}
                helperText={error?.message}
                fullWidth
              />
            )}
          />

          <Controller
            name="totalScore"
            control={control}
            rules={{ required: '请输入总分' }}
            render={({ field, fieldState: { error } }) => (
              <TextField
                {...field}
                label="总分"
                type="number"
                inputProps={{ min: 1, max: 1000 }}
                error={!!error}
                helperText={error?.message}
                fullWidth
              />
            )}
          />

          <Controller
            name="passingScore"
            control={control}
            rules={{ required: '请输入及格分' }}
            render={({ field, fieldState: { error } }) => (
              <TextField
                {...field}
                label="及格分"
                type="number"
                inputProps={{ min: 1, max: 1000 }}
                error={!!error}
                helperText={error?.message}
                fullWidth
              />
            )}
          />

          <Controller
            name="questions"
            control={control}
            render={({ field: { value, onChange } }) => (
              <ExamQuestions
                examId={initialValues?.id}
                subject={subject}
                onQuestionsChange={onChange}
                initialQuestions={value}
              />
            )}
          />

          <Button
            type="submit"
            variant="contained"
            disabled={loading}
          >
            {submitText}
          </Button>
        </Stack>
      </form>
    </LocalizationProvider>
  );
}